package kburndown.client.service.data
{
	import flash.ui.Mouse;
	
	import kburndown.client.app.layout.LayoutManager;
	import kburndown.client.app.layout.core.layout_internal;
	import kburndown.client.app.utils.DateHelper;
	import kburndown.client.app.utils.IconLib;
	import kburndown.client.service.KBurndownService;

	public class ProjectInfo
	{
		public static var OneDay: Number = (1000 * 60 * 60 * 24);

		public function ProjectInfo(key: SingletonKey)
		{
		}

		private static var _instance: ProjectInfo;

		public static function get instance(): ProjectInfo
		{
			if (!_instance)
			{
				_instance = new ProjectInfo(new SingletonKey());
			}
			return _instance;
		}

		public var description: String;
		public var name: String;
		public var memberCount: int;
		public var units: Vector.<UnitInfo> = new Vector.<UnitInfo>();
		public var startDate: Date;
		public var endDate: Date;
		public var dayResults: Vector.<DayResult> = new Vector.<DayResult>();

		//这名字很挫  取得项目延期的最后一天
		public function getWorseDay(): Date
		{
			var mostTime: Number = 0;
			for(var unitIndex: int = 0; unitIndex < units.length; unitIndex ++)
			{
				var unit: UnitInfo = units[unitIndex];
				var curreentTime: Number = DateHelper.getToday().time;
				for(var taskIndex: int = 0; taskIndex < unit.tasks_undone.length; taskIndex++)
				{
					var taskInfo: TaskInfo = unit.tasks_undone[taskIndex];
					curreentTime += (taskInfo.duration * OneDay);
				}
				if(curreentTime > mostTime)
					mostTime = curreentTime;
			}
			mostTime += OneDay;
			return new Date(mostTime);
		}
		
		public function get duration(): Number
		{
			return (endDate.time - startDate.time) / OneDay;
		}
		
		public function get actualDuration(): int
		{
			var worseDuration :Number  = DateHelper.getDayCountBetween(
				startDate, getWorseDay());
			var _actualDuration: int = Math.max(duration, worseDuration);
			return _actualDuration;
		}

		public function get allTimeCount(): Number
		{
			return duration * unitsCount;
		}

		public function get unitsCount(): int
		{
			return units.length;
		}

		public function setProjectData(result: Object): void
		{
			this.description = result["description"];
			this.name = result["name"];
			this.memberCount = result["member_count"];
			this.endDate = result["end_date"] as Date;
			this.startDate = result["start_date"] as Date;
		}

		public function setUnitData(result: Object): void
		{
			var length: int = result.length;
			for (var i: int = 0; i < length; i++)
			{
				var item: Object = result[i];
				var unit: UnitInfo = new UnitInfo();
				unit.id = item["id"];
				unit.name = item["name"];
				unit.memberCount = item["member_count"];
				unit.style = item["style"];
				unit.posX = item["pos_x"];
				unit.posY = item["pos_y"];
				units.push(unit);
			}
		}
		
		public function setTasksData(result: Object): void
		{
			var taskLength: int = result.length;
			for (var i: int = 0; i < taskLength; i++)
			{
				var item: Object = result[i];
				var taskInfo: TaskInfo = new TaskInfo();
				var owner: UnitInfo = UnitInfo.getUnitById(item.owner.id);
				setTaskInfoData(taskInfo, item);
				taskInfo.owner = owner;
				if (!taskInfo.deleted)
					owner.tasks.push(taskInfo);
			}
			
			for(var unitIndex: int = 0; unitIndex < units.length; unitIndex++)
			{
				var unit: UnitInfo = units[unitIndex];
				unit.tasks = unit._sortTasks(unit.tasks);
			}
		}

		public function setBurndownGraphData(result: Object): void
		{
//			dayResults.length = 0;
//			var length: int = result.length;
//			for (var i: int = 0; i < length; i++)
//			{
//				var dayInfo: DayResult = new DayResult();
//				if (i < length)
//				{
//					var item: Object = result[i];
//					dayInfo.date = item["date"] as Date;
//					dayInfo.value = item["value"];
//				}
//				dayResults.push(dayInfo);
//			}
			updataGraphData();
		}

		public function setTasksDataByUnit(unitId: int, result: Object): void
		{
			var taskLength: int = result.length;
			var unit: UnitInfo = UnitInfo.getUnitById(unitId);
			for (var i: int = 0; i < taskLength; i++)
			{
				var item: Object = result[i];
				var taskInfo: TaskInfo = new TaskInfo();
				setTaskInfoData(taskInfo, item);
				taskInfo.owner = unit;
				unit.tasks.push(taskInfo);
			}
		}
		
		public function setTaskInfoData(taskInfo: TaskInfo, item: Object): void
		{
			taskInfo.content = item["content"];
			taskInfo.deleted = item["deleted"];
			taskInfo.duration = item["duration"];
			taskInfo.finishedComment = item["finish_comment"];
			taskInfo.finishedDate = item["finish_date"] as Date;
			taskInfo.id = item["id"];
			taskInfo.name = item["name"];
			taskInfo.priority = item["priority"];
			taskInfo.icon = item["icon"];
		}
		
		public function setTaskReOpen(task: TaskInfo, anchorTaskId: int): void
		{
			//update graph data
			for(var i:int = 0; i < dayResults.length; i++)
			{
				if(dayResults[i].date.time >= task.finishedDate.time)
				{
					dayResults[i].value += task.duration;
				}
			}
			
			var unit: UnitInfo = task.owner;
			unit.setTaskReopen(task, anchorTaskId);
		}
		
		public function changeTodayResult(value: Number): void
		{
			var dayResult: DayResult = dayResults[dayResults.length - 1];
			dayResult.value += value;
//			LayoutManager.instance.updataBurndown();
		}

		public function addTaskByData(task: TaskInfo): void
		{
			var unit: UnitInfo = task.owner;
			unit.tasks.push(task);
			unit.tasks_undone.push(task);
		}
		
		public function updataGraphData(): void
		{
			dayResults.length = 0;
			var dayIndex: int;
			var taskIndex: int ;
			var _duration: int =DateHelper.getDayCountBetween(startDate, DateHelper.getToday());
			//			_duration += 2;
			var _dayresults: Vector.<DayResult> = new Vector.<DayResult>();
			for (dayIndex = 0; dayIndex < _duration; dayIndex++)
			{
				var dayResult: DayResult = new DayResult();
				dayResult.value = allTimeCount;
				dayResult.date = new Date(startDate.time + (dayIndex * OneDay));
				if((dayIndex==0) || (dayIndex == _duration-1) || (dayResult.date.day == 1))
				{
					dayResults.push(dayResult);
				}
				_dayresults.push(dayResult);
			}
			
			for (taskIndex = 0; taskIndex < tasks.length; taskIndex++)
			{
				if (tasks[taskIndex].finishedDate)
				{
					var finishedDayIndex: int = getDayIndex(tasks[taskIndex].finishedDate);
					for (dayIndex = finishedDayIndex; dayIndex < _dayresults.length; dayIndex++)
					{
						_dayresults[dayIndex].value -= tasks[taskIndex].duration;
					}
				}
			}
		}

		public function get tasks(): Vector.<TaskInfo>
		{
			//Project . tasks 
			//尽量不要多次调用它，它是要计算的。。。。。。。。。
			var _tasks: Vector.<TaskInfo> = new Vector.<TaskInfo>();
			var unitsLength: int = units.length;
			for(var i: int = 0; i < unitsLength; i++)
			{
				var unit: UnitInfo = units[i];
				var taskLength: int = unit.tasks.length;
				for(var taskIndex: int = 0; taskIndex < taskLength; taskIndex++)
				{
					_tasks.push(unit.tasks[taskIndex]);
				}
			}
			return _tasks;
		}
		
		public function getTaskById(taskId: int): TaskInfo
		{
			var unitsLength: int = units.length;
			for(var i: int = 0; i < unitsLength; i++)
			{
				var unit: UnitInfo = units[i];
				var taskCount: int = unit.tasks.length;
				for(var taskIndex: int = 0; taskIndex < taskCount; taskIndex++)
				{
					var task: TaskInfo = unit.tasks[taskIndex];
					if(taskId == task.id)
						return task;
				}
			}
			return null;
		}
		
		public function importData(callback: Function): void
		{
			
//			startDate = new Date(2010,8,8,8);
//			endDate = new Date(2010, 10, 8, 8);
			startDate = new Date(DateHelper.getToday().time - 34 * OneDay);
			endDate = new Date(DateHelper.getToday().time + 25 * OneDay);
//			startDate = new Date(DateHelper.getToday().time - 62 * OneDay);
//			endDate = new Date(DateHelper.getToday().time + 1 * OneDay);
			var iconList: Array = IconLib.getIconList();
			var taskIDCount: int = 1;
			
			var taskIndex:int;
			var dayIndex:int;
			var unit: UnitInfo;
			var taskInfo: TaskInfo;
			for (var i: int = 0; i < 4; i++)
			{
				var unitData: Object = DataBase.data[i];
				unit = new UnitInfo();
				unit.id = i + 1;
				unit.name = unitData.name;
				unit.style = unitData.style;
				unit.posX = unitData.pos_x;
				unit.posY = unitData.pos_y;
				var tasksData: Array = unitData.tasks as Array;
				for (taskIndex = 0; taskIndex < tasksData.length; taskIndex++)
				{
					var taskData: Object = tasksData[taskIndex];
					taskInfo = new TaskInfo();
					taskInfo.id = taskIDCount;
					taskIDCount ++;
					taskInfo.icon = iconList[taskInfo.id].key;
					taskInfo.name =  taskData.name;
					taskInfo.content = taskData.content;
					taskInfo.owner = unit;
					var finishedDate: Date = new Date(startDate.time + taskData.finishedData * OneDay);
					if(finishedDate.time > DateHelper.getToday().time)
					{
						taskInfo.priority = taskIndex;
					}
					else
					{
						taskInfo.priority = -1 * taskIndex;
						taskInfo.finishedDate = finishedDate;
					}
					taskInfo.duration = taskData.duration;
					unit.tasks.push(taskInfo);
					createAddTaskTrace(taskInfo);
				}
				unit.tasks = unit._sortTasks(unit.tasks);
				units.push(unit);
			}
			
			updataGraphData();
			createTraceInfo();
			callback();
		}
		
		public function createTraceInfo(): void
		{
			var unit: UnitInfo;
			var unitIndex: int; 
			var taskIndex: int;
			for(unitIndex= 0; unitIndex < units.length; unitIndex ++)
			{
				unit = units[unitIndex];
				for(taskIndex = 0; taskIndex < unit.tasks_done.length;taskIndex++)
				{
					//					finish_task(None, 1, "给您添蘑菇了")
					var finishedTask: String = "finish_task(None, ";
					finishedTask += unit.tasks_done[taskIndex].id;
					finishedTask += ", \"给您添蘑菇了\")";
					trace(finishedTask);
					//					update kburndown_task set finish_date = "2010-10-05" where id = 1
				}
				//update common_info set value = @msg_count+ 1
				//where name = 'msg_count' and value = @msg_count
			}
			
			for(unitIndex= 0; unitIndex < units.length; unitIndex ++)
			{
				unit = units[unitIndex];
				for(taskIndex = 0; taskIndex < unit.tasks_done.length;taskIndex++)
				{
					var _finishDate: Date =  unit.tasks_done[taskIndex].finishedDate;
					var sqlDate: String = _finishDate.fullYear + "-" + (_finishDate.month+1) + "-" + _finishDate.date;
					var sqlString: String = "update kburndown_task set finish_date = \"";
					sqlString += sqlDate;
					sqlString += "\" where id = ";
					sqlString += unit.tasks_done[taskIndex].id;
					sqlString += ";";
					trace(sqlString);
				}
			}
			
			var dayIndex: int = 0;
			var dayResult: DayResult;
			for(dayIndex = 0; dayIndex < dayResults.length; dayIndex++)
			{
				dayResult = dayResults[dayIndex];
				//					update kburndown_graphdata set value = 23 where id = 1
				var dayResultString: String = "update kburndown_graphdata set value = ";
				dayResultString += dayResult.value;
				dayResultString += " where id = ";
				dayResultString += (dayIndex + 1);
				dayResultString += ";";
				trace(dayResultString);
			}
		}
		
		private function createAddTaskTrace(taskInfo: TaskInfo): void
		{
			
			//					add_task(None, "azhe-1", "azhe酱油1", 1, 1)
			var taskString: String = "add_task(None, \"";
			taskString += taskInfo.name;
			taskString += "\", \"";
			taskString += taskInfo.content;
			taskString += "\", \"";
			taskString += taskInfo.icon;
			taskString += "\", ";
			taskString += taskInfo.owner.id;
			taskString += ", ";
			taskString += taskInfo.duration;
			taskString += ")";
			trace(taskString);
		}

		public function getDayIndex(date: Date): int
		{
			return (date.time - startDate.time) / OneDay;
		}
	}
}

class SingletonKey
{
}